<template>
    <div>
        <div class="container">
            <div class="handle-box">
                <el-input v-model="query.name" placeholder="用户名模糊查询" class="handle-input mr10"></el-input>
                <el-col :span="2">
                    <el-select v-model="query.status" placeholder="状态查询用户" :style="{ width: '100%' }">
                        <el-option
                            v-for="(item, index) in statusOptions"
                            :key="index"
                            :label="item.label"
                            :value="item.value"
                            :disabled="item.disabled"
                        ></el-option>
                    </el-select>
                </el-col>
                <el-button type="primary" @click="Show()">查询</el-button>
                <el-button type="danger" @click="Delete()">批删</el-button>
                <el-button type="success" @click="dialogFormVisible = true">添加</el-button>
                <el-button type="primary" @click="OpenUserRole()">为用户分配角色</el-button>
            </div>
            <el-row>
                <el-col :span="4">
                    <div class="grid-content bg-purple">
                        <el-button type="text" style="font-size: 20px" @click="DepShow">全部显示>>></el-button>
                        <el-tree
                            default-expand-all
                            :expand-on-click-node="false"
                            :data="DeparData"
                            :props="defaultProps"
                            @node-click="Sh"
                        ></el-tree>
                    </div>
                </el-col>
                <el-col :span="20">
                    <el-table
                        ref="multipleTable"
                        :data="tableData"
                        tooltip-effect="dark"
                        style="width: 100%"
                        @selection-change="handleSelectionChange"
                    >
                        <el-table-column type="selection" width="55"></el-table-column>
                        <el-table-column label="账号" width="120" prop="account"> </el-table-column>
                        <el-table-column label="姓名" width="120">
                            <template slot-scope="scope">{{ scope.row.uName }}</template>
                        </el-table-column>
                        <el-table-column prop="roles" label="角色" show-overflow-tooltip width="200"> </el-table-column>
                        <el-table-column label="状态" width="100">
                            <template slot-scope="scope">
                                {{ scope.row.status == 1 ? '启用' : '禁用' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="createdTime" label="创建时间" width="150"> </el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit"  @click="Editor(scope.row.uId)">编辑 </el-button>
                                <el-button type="danger" icon="el-icon-delete"  @click="Deletes(scope.row.uId)">删除 </el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <div class="pagination">
                        <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="query.pageIndex"
                            :page-sizes="[10, 20, 30, 40]"
                            :page-size="query.pageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="total"
                        >
                        </el-pagination>
                    </div>
                </el-col>
            </el-row>
        </div>

        <el-dialog title="分配用户角色" :visible.sync="userRoledialog">
            <el-table
                ref="multipleRole"
                :data="tableDataRole"
                tooltip-effect="dark"
                style="width: 100%"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55"> </el-table-column>
                <el-table-column label="ID" width="120">
                    <template slot-scope="scope">{{ scope.row.rId }}</template>
                </el-table-column>
                <el-table-column prop="rName" label="角色名" width="120"> </el-table-column>
                <el-table-column prop="rText" label="具体描述" show-overflow-tooltip> </el-table-column>
            </el-table>

            <div slot="footer" class="dialog-footer">
                <el-button @click="userRoledialog = false">取 消</el-button>
                <el-button type="primary" @click="AddUserRole">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog title="编辑用户" :visible.sync="EditorUser">
            <el-form ref="elForm" :model="Data" :rules="rules" size="medium" label-width="100px">
                <el-form-item label="用户账号" prop="account">
                    <el-input v-model="Data.account" placeholder="请输入用户账号" :disabled="true" :style="{ width: '100%' }"></el-input>
                </el-form-item>
                <el-form-item label="用户密码" prop="password">
                    <el-input v-model="Data.password" placeholder="请输入用户密码" show-password :style="{ width: '100%' }"></el-input>
                </el-form-item>
                <el-form-item label="真实姓名" prop="uName">
                    <el-input v-model="Data.uName" placeholder="请输入真实姓名" :style="{ width: '100%' }"></el-input>
                </el-form-item>
                <el-form-item label="启用/禁用" prop="status">
                    <el-switch v-model="Data.status"></el-switch>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="EditorUser = false">取消</el-button>
                <el-button type="primary" @click="UserUpt">确定</el-button>
            </div>
        </el-dialog>
        <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
            <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
                <el-form-item label="用户账号" prop="account">
                    <el-input v-model="formData.account" placeholder="请输入用户账号" :style="{ width: '100%' }"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="formData.password" placeholder="请输入密码" show-password :style="{ width: '100%' }"> </el-input>
                </el-form-item>
                <el-form-item label="确定密码" prop="passwords">
                    <el-input v-model="formData.passwords" placeholder="请输入确定密码" show-password :style="{ width: '100%' }">
                    </el-input>
                </el-form-item>
                <el-form-item label="真实姓名" prop="uName">
                    <el-input v-model="formData.uName" placeholder="请输入真实姓名" :style="{ width: '100%' }"></el-input>
                </el-form-item>
                <el-form-item label="启用/禁用" prop="status">
                    <el-switch v-model="formData.status"></el-switch>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="close">取消</el-button>
                <el-button type="primary" @click="AddUser">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getUsers, addUser, deleteUser, addUserRole, findUser, updateUser } from '@/api/user';
import { getRoleList } from '@/api/role';
import { DeparTreeShow } from '@/api/departments';
export default {
    name: 'user',
    data() {
        return {
            //部门数据
            DeparData: [],
            defaultProps: {
                children: 'dlist',
                label: 'name',
                value: 'depId'
            },
            //获取部门Id
            did: 0,
            //用户查询
            query: {
                name: undefined,
                status: undefined,
                pageIndex: 1,
                pageSize: 10
            },
            statusOptions: [
                {
                    label: '全部',
                    value: undefined
                },
                {
                    label: '启用',
                    value: 'true'
                },
                {
                    label: '禁用',
                    value: 'false'
                }
            ],
            //获取选中角色的数组
            multipleRole: [],
            //用户列表
            tableData: [],
            //总行数
            total: 0,
            //获取选中用户的数据
            multipleSelection: undefined,
            //添加用户对话框
            dialogFormVisible: false,
            //编辑用户对话框
            EditorUser: false,
            //添加用户
            formData: {
                account: undefined,
                password: undefined,
                passwords: undefined,
                uName: undefined,
                status: true
            },
            //编辑用户
            Data: {
                userid: undefined,
                account: undefined,
                password: undefined,
                uName: undefined,
                status: true
            },
            rules: {
                account: [
                    {
                        required: true,
                        message: '请输入用户账号',
                        trigger: 'blur'
                    }
                ],
                password: [
                    {
                        required: true,
                        
                        message: '请输入密码',
                        trigger: 'blur'
                    },
                    { min: 6, max: 15, message: '密码长度应大于等于6个字符小于15个字符!', trigger: "blur" },
                ],
                passwords: [
                    {
                        required: true,
                        message: '请输入确定密码',
                        trigger: 'blur'
                    },
                    {
                        trigger: 'blur',
                        validator: (rule, value, callback) => {
                            if (value !== this.formData.password) {
                                callback(new Error('两次输入密码不一致'))
                            } else {
                                callback()
                            }
                        }
                    }
                ],
                uName: [
                    {
                        required: true,
                        message: '请输入真实姓名',
                        trigger: 'blur'
                    }
                ]
            },
            //对话框宽度
            formLabelWidth: '120px',
            //添加用户角色
            userRole: {
                uid: undefined,
                rid: undefined
            },
            //添加用户角色对话框
            userRoledialog: false,
            //角色列表
            tableDataRole: []
        };
    },
    methods: {
        //第一步调用
        //用户的显示
        async Show() {
            await getUsers(this.query).then((res) => {
                //console.log('用户列表:', res);
                this.tableData = res.data.list;
                this.total = res.data.total;
            });
        },
        //第二部调用
        //部门树形显示
        async DepartShow() {
            await DeparTreeShow().then((res) => {
                //console.log(str);
                this.DeparData = res.data;
                //console.log(this.DeparData);
            });
        },

        async CallInOrder() {
            await this.Show();
            await this.DepartShow();
        },

        //用户编辑
        Editor(cc) {
            findUser({ id: cc }).then((res) => {
                console.log('用户信息', res);
                this.Data.userid = res.data.uId;
                this.Data.account = res.data.account;
                this.Data.password = res.data.password;
                this.Data.uName = res.data.uName;
                this.Data.status = res.data.status;
                console.log(this.Data);
                this.EditorUser = true;
            });
        },
        //用户修改
        UserUpt() {
            let data = {
                uid: this.Data.userid,
                uName: this.Data.uName,
                password: this.Data.password,
                status: this.Data.status
            };
            updateUser(data).then((res) => {
                //console.log('用户删除:', res);
                if (res.data > 0) {
                    this.$message({
                        message: '用户修改成功',
                        type: 'success'
                    });
                    this.Show();
                } else if (res.data == 0) {
                    this.$message({
                        message: '输入密码与原密码相同,请重新输入',
                        type: 'warning'
                    });
                } else {
                    this.$message({
                        message: '用户修改失败',
                        type: 'warning'
                    });
                }
                this.EditorUser = false;
                this.Show();
            });
        },

        //根据部门树形进行查询
        Sh(row) {
            //console.log(row);
            this.did = row.depId;
            //console.log(this.did);
            let data = {
                DepId: this.did,
                Name: this.query.name,
                PageIndex: this.query.pageIndex,
                PageSize: this.query.pageSize
            };
            getUsers(data).then((str) => {
                //console.log('用户列表:', str);
                this.tableData = str.data.list;
                this.total = str.data.total;
            });
        },
        DepShow() {
            this.Show();
        },
        //页容量
        handleSizeChange(val) {
            //console.log(`每页 ${val} 条`);
            this.query.pageSize = val;
            this.Show();
        },
        //上一页下一页
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.query.pageIndex = val;
            this.Show();
        },
        //全选反选
        handleSelectionChange(val) {
            this.multipleSelection = val;
            this.multipleRole = val;
        },
        //用户批删
        Delete() {
            var ids = this.multipleSelection.map((x) => x.uId).toString();
            //console.log('用户批删:', ids);
            ///使用element-ui 提示
            this.Deletes(ids)
        },
        //用户单删
        Deletes(Ids) {
            this.$confirm('此操作将执行永久删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //调用删除接口
                deleteUser({ Ids }).then((res) => {
                    //console.log('用户删除:', res);
                    if (res.data > 0) {
                        this.$message({message: '用户删除成功',type: 'success'});
                        this.Show();
                    } else {
                        this.$message({message: '用户删除失败',type: 'warning'});
                    }
                });
            }).catch(() => {
            });
        },
        //用户的添加
        AddUser() {
            addUser(this.formData).then((res) => {
                //console.log('用户添加:', res);
                if (res.data > 0) {
                    this.$message({
                        message: '用户添加成功',
                        type: 'success'
                    });
                    this.dialogFormVisible = false;
                    this.Show();
                } else if ((res.msg = '账号已经存在,请重新输入!')) {
                    this.$message({
                        message: '账户已经存在,请重新输入!',
                        type: 'warning'
                    });
                    this.formData = [];
                } else {
                    this.$message({
                        message: '用户添加失败',
                        type: 'warning'
                    });
                    this.dialogFormVisible = false;
                }
                this.formData = [];
            });
        },
        //打开角色关系的添加
        OpenUserRole() {
            // console.log('用户:', this.multipleSelection);
            if (this.multipleSelection === undefined || this.multipleSelection.length === 0 || this.multipleSelection.length > 1) {
                this.$message({
                    message: '请选择一个用户',
                    type: 'warning'
                });
                return;
            } else {
                //角色列表
                this.ShowRole();
                this.userRoledialog = true;
                this.userRole.uid = parseInt(this.multipleSelection.map((x) => x.uId).toString());
                //console.log('角色关系 uid:', this.userRole.uid);
            }
        },
        //显示角色
        ShowRole() {
            getRoleList().then((res) => {
                //console.log('角色列表:', res);
                this.tableDataRole = res.data.pageList;
            });
        },
        //关闭添加用户弹出框
        close() {
            this.dialogFormVisible = false;
        },
        //添加用户角色关系
        AddUserRole() {
            this.userRole.rid = this.multipleRole.map((x) => x.rId).toString(); //拿到了用户选中的角色Id，例如：“11,13”
            addUserRole(this.userRole).then((res) => {
                // console.log('角色用户关系:', res);
                if (res.data > 0) {
                    this.$message({
                        message: '用户角色关系添加成功',
                        type: 'success'
                    });

                    this.userRoledialog = true;
                } else {
                    this.$message({
                        message: '用户角色关系添加失败',
                        type: 'warning'
                    });
                }
                this.userRoledialog = false;
                this.Show();
            });
        }
    },

    mounted() {
        //调用
        this.CallInOrder();
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
